/**
    Copyright (C) 2011  Alexander Vollmer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jefb.web.model;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.jefb.entity.RoleEntity;
import org.jefb.entity.UserEntity;
import org.jefb.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;

@Component("userModel")
@Scope("session")
public class UserModel extends EntityModel<UserEntity> implements Serializable {

	@Autowired
	private IUserService userService;

	private static final long serialVersionUID = -7617301683014677873L;
	private String password;
	private String confirmPassword;

	public UserModel() {
	}

	public void resetModel() {
		password = null;
		confirmPassword = null;
	}

	public Collection<RoleEntity> getAssignedRoles() {
		if (getModel().getSelectedEntity() != null) {
			return userService.getRoles(getModel().getSelectedEntity());
		} else {
			return null;
		}
	}

	public List<RoleEntity> getUnassignedRoles() {
		if (getModel().getSelectedEntity() != null) {
			return userService.getUnassignedRoles(getModel()
					.getSelectedEntity());
		} else {
			return null;
		}
	}
	
	public ListitemRenderer getRoleListitemRenderer(){
		return new RoleListRenderer();
	}
	
	private static class RoleListRenderer implements ListitemRenderer{
		public void render(Listitem li, Object data) throws Exception {
			RoleEntity p = (RoleEntity) data;
			new Listcell(p.getAuthority()).setParent(li);
			li.setAttribute("roleEntity", data);
		}
	}

	/**
	 * @return
	 */
	public EntityModel<UserEntity> getModel() {
		return this;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public IUserService getUserService() {
		return userService;
	}

}
